-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2013Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
-- File format:
-- ...
-- 0x44,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x11,
-- 0x55,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x22,
-- 0x66,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x33,
-- ...
function Read_File(file_name)
	-- print("file_name: " .. file_name)
	local file = io.open(file_name, "r")

	local raw_data = {}
	local data = 0
	local line_num = 1

	for line in file:lines() do
		for i=1, line:len()/5 do
			 data = tonumber(line:sub(5 * i - 2 , 5 * i-1), 16)
			 if type(data) == "number" then
			 	raw_data[#raw_data + 1] = data
			 else
			 	print("Error to convert line: " .. line_num .. " of: " .. line:sub(5 * i - 2 , 5 * i-1) )
			 end 
		end
		line_num = line_num + 1
	end
	
	file:close()
	
	return raw_data
end

-- -----------------------------------------------------------------------------
g_raw_data = {}

g_raw_data = Read_File(arg[1])

if type(g_raw_data) == "table" then
	for i=1, #g_raw_data do
		io.write(string.format("%02xH,", g_raw_data[i]):upper())
		if i%16 == 0 then
			print("")
		end
	end
else
	print("Fail to read data file, please check file name and file format")
	return
end

if #g_raw_data > 0 then
	local file_name = "txtHexToBin_" .. string.format("%.3fKB", #g_raw_data/1024.0):upper() 
	file_name = file_name .. os.date("_%Y.%m.%d_%H%M%S") .. ".bin"
    local file_w = io.open(file_name, "wb")
    for i = 1, #g_raw_data do
        file_w:write(string.char(g_raw_data[i]))
    end
    file_w:close()
end